<template>
  <view class="product-page">
    <!-- 顶部导航栏 -->
<!--    <view class="navbar">
      <view class="back-button" @click="handleBack">
        <image src="/static/xiangzuo_1.png" mode="aspectFit" class="back-icon"></image>
      </view>
      <text class="title">商品管理</text>
      <view class="right-placeholder"></view>
    </view> -->

    <!-- 商品列表区域 -->
    <view class="product-list">
      <view v-if="products.length > 0" class="list-container">
        <view v-for="product in products" :key="product.id" class="product-item">
          <view class="product-info">
            <image :src="product.image" mode="aspectFit" class="product-image"></image>
            <view class="product-details">
              <text class="product-title">{{ product.title }}</text>
              <text class="product-category">{{ getCategoryName(product.category_id) }}</text>
              <view class="product-price-weight">
                <text class="product-price">¥{{ product.price }}</text>
                <text class="product-weight">权重: {{ product.weigh }}</text>
              </view>
            </view>
          </view>
          <view class="action-buttons">
            <view class="action-button edit-button" @click="editProduct(product.id)">
              <image src="/static/xiugai07_1.png" mode="aspectFit" class="action-icon"></image>
            </view>
            <view class="action-button delete-button" @click="deleteProduct(product.id)">
              <image src="/static/shanchu_1.png" mode="aspectFit" class="action-icon"></image>
            </view>
          </view>
        </view>
      </view>
      <view v-else class="empty-state">
        <text>暂无商品数据</text>
      </view>
    </view>

    <!-- 添加商品按钮 -->
    <view class="add-button" @click="showAddProductModal">
      <image src="/static/tianjia_2.png" mode="aspectFit" class="add-icon"></image>
      <text class="add-text">添加商品</text>
    </view>

    <!-- 弹窗组件 -->
    <uv-popup ref="popup" :show="showPopup" mode="bottom" @change="change">
      <view class="modal-container">
        <view class="modal-header">
          <text class="modal-title">{{ isEditing ? '编辑商品' : '添加商品' }}</text>
        </view>
        
        <view class="modal-content">
          <view class="form-item">
            <text class="label">商品标题</text>
            <input type="text" v-model="formData.title" placeholder="请输入商品标题" class="input-field">
          </view>
          
          <view class="form-item">
            <text class="label">商品分类</text>
            <view class="category-selector" @click="showCategoryPicker">
              <text class="category-text">{{ selectedCategoryName || '请选择商品分类' }}</text>
              <image src="/static/jiantou2_3.png" mode="aspectFit" class="arrow-icon"></image>
            </view>
          </view>
          
          <view class="form-item">
            <text class="label">商品主图</text>
            <view class="image-upload">
              <image :src="formData.images" mode="aspectFit" class="preview-image"></image>
              <view class="upload-placeholder" @click="uploadImage">
                <image src="/static/paizhao_1.png" mode="aspectFit" class="upload-icon"></image>
                <text class="upload-text">点击上传</text>
              </view>
            </view>
          </view>
             
          <view class="form-item">
            <text class="label">商品价格</text>
            <input type="number" v-model="formData.price" placeholder="请输入商品价格" class="input-field">
          </view>
          
          <view class="form-item">
            <text class="label">权重</text>
            <input type="number" v-model="formData.weigh" placeholder="请输入权重，数字越大排序越靠前" class="input-field">
          </view>
        </view>
        
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeModal">取消</view>
          <view class="confirm-btn" @click="saveProduct">确定</view>
        </view>
      </view>
    </uv-popup>

    <!-- 分类选择器 -->
        <uv-picker 
          ref="categoryPopup"
          :columns="categories" 
          keyName="name"
          @confirm="onCategoryChange"
        ></uv-picker>
  </view>
</template>

<script>
	const baseUrl='https://1010.10906.cn/shop/'
import uvPopup from '@/uni_modules/uv-popup/components/uv-popup/uv-popup.vue'
import { getgoodscategoryindex, getcommonupload,getproductadd, getproductdel, getproductedit, getproductindex,getproductedits } from '../../api';
import store from '@/store'
export default {
  components: {
    uvPopup
  },
  data() {
    return {
      products: [],
      categories: [],
      showPopup: false,
      isEditing: false,
      editingId: null,
      selectedCategoryIndex: -1,
      selectedCategoryName: '',
	  imgurlone:'',
      formData: {
        title: '',
        category_id: '',
        image: '1111',
        price: '',
        weigh: '' ,// 默认权重
		images:''
      }
    }
  },
  onShow() {
    this.init()
  },
  methods: {
    // 初始化数据
    async init() {
      // 获取商品分类数据
      await this.getCategories()
      // 获取商品列表数据
      await this.getProducts()
    },

    // 获取商品分类
    async getCategories() {
      try {
        let res = await getgoodscategoryindex({shopid:store.state.user.userInfo.id, page: '1', limit: 100})
       	
		if (res.data.code == 1) {
		
          this.categories =[[...res.data.data.rows] ]
		  console.log('res111',this.categories)
        }
      } catch (error) {
        console.error('获取分类失败:', error)
      }
    },

    // 获取商品列表
    async getProducts() {
      try {
        let res = await getproductindex({shopid:store.state.user.userInfo.id, page: '1', limit: 100})
        if (res.data.code === 1) {
			console.log('res2121212',res.data.data.rows)
          this.products = res.data.data.rows
		this.getCategoryName();
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
      }
    },

    // 返回上一页
    handleBack() {
      uni.navigateBack()
    },

    // 显示添加商品弹窗
    showAddProductModal() {
      this.isEditing = false
      this.editingId = null
      this.resetForm()
      this.$refs.popup.open()
    },

    // 编辑商品
  async  editProduct(id) {
      // const product = this.products.find(item => item.id === id)
	  // console.log('product',product)
	  let res=await  getproductedits({shopid:store.state.user.userInfo.id, ids: id})
	  console.log('ressss',res.data.code)
      if (res.data.code==1) {
        this.isEditing = true
        this.editingId = id
        this.formData =res.data.data
		this.formData.images=res.data.data.image;
        this.selectedCategoryName = this.getCategoryName(res.data.data.category_id)
        this.$refs.popup.open()
		
      }
    },

    // 删除商品
    deleteProduct(id) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个商品吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              let result = await getproductdel({shopid:store.state.user.userInfo.id, ids: id})
              if (result.data.code === 1) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
                this.getProducts() // 重新获取商品列表
              }
            } catch (error) {
              console.error('删除商品失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    // 保存商品
    async saveProduct() {
      // 表单验证
      if (!this.formData.title) {
        uni.showToast({
          title: '请输入商品标题',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.category_id) {
        uni.showToast({
          title: '请选择商品分类',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.image) {
        uni.showToast({
          title: '请上传商品主图',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.price || this.formData.price < 0) {
        uni.showToast({
          title: '请输入正确的商品价格',
          icon: 'none'
        })
        return
      }

      try {
        if (this.isEditing) {
          // 编辑商品
		  console.log('222222223232',this.formData)
		  delete this.formData.createtime
		  delete this. formData.updatetime
          let res = await getproductedit({shopid: store.state.user.userInfo.id, ids: this.editingId, ...this.formData})
          if (res.data.code === 1) {
            uni.showToast({
              title: '更新成功',
              icon: 'success'
            })
            this.$refs.popup.close()
            this.getProducts() // 重新获取商品列表
          }
        } else {
          // 添加商品
          let res = await getproductadd({shopid:store.state.user.userInfo.id, ...this.formData})
          if (res.data.code === 1) {
            uni.showToast({
              title: '添加成功',
              icon: 'success'
            })
            this.$refs.popup.close()
            this.getProducts() // 重新获取商品列表
          }
        }
      } catch (error) {
        console.error('保存商品失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    },

    // 显示分类选择器
    showCategoryPicker() {
		this.getCategories()
      this.$refs.categoryPopup.open()

    },

    // 关闭分类选择器
    closeCategoryPicker() {
      this.$refs.categoryPopup.close()
    },

    // 确认分类选择
    confirmCategory() {
		console.log('index',this.selectedCategoryIndex)
		console.log('this.categories[this.selectedCategoryIndex]',this.categories[0][this.selectedCategoryIndex])
      if (this.selectedCategoryIndex !== -1 && this.categories[0][this.selectedCategoryIndex]) {
		  console.log('222222222222')
        const category = this.categories[0][this.selectedCategoryIndex]
        this.formData.category_id = category.id
        this.selectedCategoryName = category.name
		console.log(' this.selectedCategoryName', this.categories[this.selectedCategoryIndex])
      }
      this.closeCategoryPicker()
    },

    // 分类选择变化
    onCategoryChange(e) {
		console.log('e111111111111111111111',e)
      this.selectedCategoryIndex = e.indexs[0]
	  this.confirmCategory()
    },

    // 上传图片
    uploadImage() {
				// 限制只能选择1张图片
				uni.chooseImage({
					count: 1, // 只允许上传1张
					sizeType: ['original'], // 只选压缩图，节省流量
					sourceType: ['album', 'camera'], // 支持相册和相机
					success: (res) => {
						// 获取选中的图片临时路径
						const tempFilePath = res.tempFilePaths[0];
						// 上传图片到服务器
						this.uploadFileone(tempFilePath);
					},
					fail: (err) => {
						console.error('选择图片失败', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
    },
			// 上传文件到服务器
			uploadFileone(tempFilePath) {
				uni.uploadFile({
					url: baseUrl + `common/upload`, // 后端上传接口
					filePath: tempFilePath,
					name: 'file', // 后端接收文件的参数名，需与后端一致
					method: 'POST',
					header: {
						token: localStorage.getItem('token')
					},
					// formData: {
					//   // 额外的表单数据，根据后端需求添加
					//   'type': 'image',
					//   'from': 'wechat-h5'
					// },
					// 监听上传进度
					// onProgressUpdate: (res) => {
					//   this.progress = res.progress;
					// },
					success: (uploadRes) => {
						// 解析后端返回结果
						try {
							const result = JSON.parse(uploadRes.data);
							if (result.code === 1 && result.data.fullurl) {
								this.formData.image =result.data.url,
                                this.formData.images=result.data.fullurl
									// this.imgurlone = result.data.fullurl
								// console.log('单独图片', this.imgurlone);

								uni.showToast({
									title: '上传成功'
								});
							} else {
								throw new Error(result.msg || '上传失败');
							}
						} catch (e) {
							console.error('上传失败', e);
							uni.showToast({
								title: e.message || '上传失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						this.imgflg = false;
						console.error('上传接口调用失败', err);
						uni.showToast({
							title: '网络错误，上传失败',
							icon: 'none'
						});
					},
					complete: () => {
						this.uploading = false;
					}
				});
			},
    // 根据分类ID获取分类名称
    getCategoryName(categoryId) {
		// console.log(categoryId);
		
      const category = this.categories[0].find(item => item.id == categoryId)
	  // console.log(category)
      return category ? category.name : '未分类'
    },

    // 重置表单
    resetForm() {
      this.formData = {
        title: '',
        category_id: '',
        image: '',
        price: '',
        weigh:''
      }
      this.selectedCategoryName = ''
      this.selectedCategoryIndex = -1
    },

    // 关闭弹窗
    closeModal() {
      this.$refs.popup.close()
    },

    // 弹窗状态变化处理
    change(e) {
      this.showPopup = e.show
    }
  }
}
</script>

<style scoped>
.product-page {
/*  padding-top: 90rpx; */
  padding-bottom: 100rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 90rpx;
  background-color: #28a745;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  z-index: 100;
}

.back-button {
  width: 40rpx;
  height: 40rpx;
}

.back-icon {
  width: 100%;
  height: 100%;
}

.title {
  color: #fff;
  font-size: 36rpx;
  font-weight: bold;
}

.right-placeholder {
  width: 40rpx;
}

/* 商品列表 */
.product-list {
  padding: 20rpx;
}

.product-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.product-info {
  display: flex;
  align-items: center;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  background-color: #f0f0f0;
}

.product-details {
  margin-left: 20rpx;
  flex: 1;
}

.product-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-category {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.product-price-weight {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 36rpx;
  color: #ff4757;
  font-weight: bold;
}

.product-weight {
  font-size: 24rpx;
  color: #999;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
}

.action-button {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 20rpx;
}

.action-icon {
  width: 40rpx;
  height: 40rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 32rpx;
}

/* 添加按钮 */
.add-button {
  position: fixed;
  bottom: 40rpx;
  right: 40rpx;
  background-color: #28a745;
  color: #fff;
  border-radius: 50%;
  width: 120rpx;
  height: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
}

.add-icon {
  width: 50rpx;
  height: 50rpx;
  margin-bottom: 8rpx;
}

.add-text {
  font-size: 24rpx;
}

/* 弹窗样式 */
.modal-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  padding-bottom: 40rpx;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.modal-content {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.input-field {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 30rpx;
  box-sizing: border-box;
}

/* 分类选择器样式 */
.category-selector {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.category-text {
  font-size: 30rpx;
  color: #666;
}

.arrow-icon {
  width: 30rpx;
  height: 30rpx;
}

/* 图片上传样式 */
.image-upload {
  width: 200rpx;
  height: 200rpx;
  border: 1rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.upload-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 28rpx;
}

/* 弹窗底部按钮 */
.modal-footer {
  display: flex;
  padding: 0 30rpx;
  margin-top: 20rpx;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  height: 90rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  margin: 0 10rpx;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #28a745;
  color: #fff;
}

/* 分类选择器弹窗样式 */
.picker-container {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30rpx;
  height: 100rpx;
  border-bottom: 1rpx solid #eee;
}

.picker-cancel,
.picker-confirm {
  font-size: 32rpx;
  color: #28a745;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}
</style>